package com.starsea.book.ui.newpage.viewmodel

import android.app.Application
import androidx.collection.arrayMapOf
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.starsea.book.base.BaseViewModel
import com.starsea.book.constant.AppConst
import com.starsea.book.help.config.ReadTipConfig.page
import com.starsea.book.help.http.newCallResponseBody
import com.starsea.book.help.http.okHttpClient
import com.starsea.book.help.http.postJson
import com.starsea.book.help.http.text
import com.starsea.book.ui.newpage.entity.BaseEntity
import com.starsea.book.ui.newpage.entity.BooRecommendEntity
import com.starsea.book.ui.newpage.entity.BookDepositoryCateEntity
import com.starsea.book.ui.newpage.entity.BookInfoEntity
import com.starsea.book.ui.newpage.entity.BookRanksTitleTypeEntity
import com.starsea.book.ui.newpage.entity.BookTabTitleEntity
import com.starsea.book.ui.newpage.entity.BoosListFilterEntity
import com.starsea.book.ui.newpage.entity.CategoryEntity
import com.starsea.book.ui.newpage.entity.CategorySortEntity
import com.starsea.book.ui.newpage.entity.HomeBannerEntity
import com.starsea.book.ui.newpage.entity.HomeDataEntity
import com.starsea.book.ui.newpage.entity.WalletWithDrawEntity
import com.starsea.book.ui.newpage.utils.gsonList
import com.starsea.book.ui.newpage.utils.gsonNormal
import com.starsea.book.utils.LogUtils
import com.starsea.book.utils.toastOnUi
import okhttp3.RequestBody.Companion.toRequestBody
import kotlin.collections.set

class HomeViewModel(application: Application) : BaseViewModel(application) {

    val dataBannerResult = MutableLiveData<BaseEntity<MutableList<HomeBannerEntity>>>()
    val dataListResult = MutableLiveData<BaseEntity<MutableList<HomeDataEntity>>>()
    val dataCategoryResult = MutableLiveData<BaseEntity<MutableList<CategoryEntity>>>()
    val dataCategoryDetailsResult = MutableLiveData<BaseEntity<MutableList<HomeDataEntity>>>()
    val dataCategoryLableResult = MutableLiveData<BaseEntity<CategorySortEntity>>()
    val onLinePersonResult = MutableLiveData<BaseEntity<String?>>()

    val fourRecommendResutl = MutableLiveData<BaseEntity<MutableList<BooRecommendEntity>>>()
    val indexRecommendResutl = MutableLiveData<BaseEntity<MutableList<BookInfoEntity>>>()
    val dataResutl = MutableLiveData<BaseEntity<MutableList<BookInfoEntity>>>()
    val topTitleResutl = MutableLiveData<BaseEntity<MutableList<BookTabTitleEntity>>>()
    val bookRanksTitleResutl = MutableLiveData<BaseEntity<BookRanksTitleTypeEntity>>()
    val bookRanksListResutl = MutableLiveData<BaseEntity<MutableList<BookInfoEntity>>>()

    val bookDepositoryCategoryResutl = MutableLiveData<BaseEntity<BookDepositoryCateEntity>>()
    val bookListFilterResutl = MutableLiveData<BaseEntity<BoosListFilterEntity>>()
    val bookDepositoryListResutl = MutableLiveData<BaseEntity<MutableList<BookInfoEntity>>>()

    val searchHistory = MutableLiveData<BaseEntity<MutableList<String>>>()
    val hotSearchCategory = MutableLiveData<BaseEntity<MutableList<BookTabTitleEntity>>>()
    val hotSearchBook = MutableLiveData<BaseEntity<MutableList<BookInfoEntity>>>()
    val keySearchBook = MutableLiveData<BaseEntity<MutableList<BookInfoEntity>>>()

//    /**
//     * 关键字搜索
//     */
//    fun getKeySearh(
//        keyword: String,
//        pageNo: Int
//    ) {
//        val map: MutableMap<String, Any> = arrayMapOf()
//        map["keyword"] = keyword
//        map["pageNo"] = pageNo
//        map["pageSize"] = 10
//        val json = Gson().toJson(map)
//        execute {
//            okHttpClient.newCallResponseBody {
//                url(AppConst.BASE_URL.plus("front-api/book/search_book"))
//                postJson(json)
//            }.text().let {
//                LogUtils.e(":>>>", ">>.${it}")
//                val entity: BaseEntity<MutableList<BookInfoEntity>> =
//                    it.gsonList(BookInfoEntity::class.java)
//                keySearchBook.postValue(entity)
//            }
//        }.onError {
//            context.toastOnUi(it.localizedMessage ?: "ERROR")
//        }
//    }


    /**
     * 热门搜索分类（前8）
     */
    fun getHotSearchCategory(
    ) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book-search/find_hot_search_type"))
                    .get()
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BookTabTitleEntity>> =
                    it.gsonList(BookTabTitleEntity::class.java)
                hotSearchCategory.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 搜索关键字历史列表
     */
    fun getHistorySearchKeyWord(
    ) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book-search/find_search_history"))
                    .get()
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<String>> =
                    it.gsonList(String::class.java)
                searchHistory.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 书库分类
     */
    fun getBookDepositoryList(
        bookState: String = "-1",
        labelTitle: String,
        pageNo: Int,
        sortType: String = "-1",
        typeId: String,
        wordCount: String = "-1"
    ) {
        val map: MutableMap<String, Any> = arrayMapOf()
        map["bookState"] = bookState
        map["labelTitle"] = labelTitle
        map["pageNo"] = pageNo
        map["sortType"] = sortType
        map["typeId"] = typeId
        map["wordCount"] = wordCount
        map["pageSize"] = 10
        val json = Gson().toJson(map)

        LogUtils.e(">>>> ,", "json = $json")

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/app_book_list"))
                    .postJson(json)
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BookInfoEntity>> =
                    it.gsonList(BookInfoEntity::class.java)
                bookDepositoryListResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 书库分类
     */
    fun getBookListFilter(value: String) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/app_book_list_filter?typeId=$value"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<BoosListFilterEntity> =
                    it.gsonNormal(BoosListFilterEntity::class.java)
                bookListFilterResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 书库分类
     */
    fun getDepositoryCategory(value: String) {
        val map: MutableMap<String, Any> = arrayMapOf()
        map["value"] = value
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/book_type_all?type=$value"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<BookDepositoryCateEntity> =
                    it.gsonNormal(BookDepositoryCateEntity::class.java)
                bookDepositoryCategoryResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 排行榜列表
     */
    fun getBookRanksListData(rankType: String, typeId: String) {
        val map: MutableMap<String, Any> = arrayMapOf()
        map["rankType"] = rankType
        map["typeId"] = typeId
        val json = Gson().toJson(map)
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/ranking_list"))
                    .postJson(json)
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BookInfoEntity>> =
                    it.gsonList(BookInfoEntity::class.java)
                bookRanksListResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 排行榜顶部标题
     */
    fun getBookRanksTitleData(value: String) {

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/ranking_filter?channelBelong=$value"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<BookRanksTitleTypeEntity> =
                    it.gsonNormal(BookRanksTitleTypeEntity::class.java)
                bookRanksTitleResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 首页顶部标题
     */
    fun getHomeTopTitle() {

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/find_header_belong"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BookTabTitleEntity>> =
                    it.gsonList(BookTabTitleEntity::class.java)
                topTitleResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    /**
     * 首页推荐
     */
    fun getFourRecommend(value: String) {

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/four_recommend_list?channelBelong=$value"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BooRecommendEntity>> =
                    it.gsonList(BooRecommendEntity::class.java)
                fourRecommendResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun getIndexRecommend(value: String) {

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/index_recommend_list?channelBelong=$value"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BookInfoEntity>> =
                    it.gsonList(BookInfoEntity::class.java)
                indexRecommendResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun getBookCityData(value: String) {

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("api/business-service/front-api/book/for_you_recommend_list?channelBelong=$value"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(":>>>", ">>.${it}")
                val entity: BaseEntity<MutableList<BookInfoEntity>> =
                    it.gsonList(BookInfoEntity::class.java)
                dataResutl.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }


    fun getOnlineNum() {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/book/find_online_count"))
            }.text().let {

                LogUtils.e(">>>> ", "data = " + it)
                val baseEntity = BaseEntity<String?>()

                val objects = JsonParser.parseString(it).asJsonObject
                baseEntity.status = objects.get("status").asInt
                baseEntity.msg = objects.get("msg").asString
                baseEntity.data = objects.get("data").asString
                onLinePersonResult.postValue(baseEntity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun getHomeBannerData() {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/home/findBannerList"))
            }.text().let {

                LogUtils.e(">>>> ", "data = " + it)
                val entity: BaseEntity<MutableList<HomeBannerEntity>> =
                    it.gsonList(HomeBannerEntity::class.java)
                dataBannerResult.postValue(entity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun getHomeData(page: Int = 1) {

        val map: MutableMap<String, Any> = arrayMapOf()
        map["pageNo"] = page
        map["pageSize"] = 10

        val json = Gson().toJson(map)
        LogUtils.e(">>> ", "json = " + json)
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/book/guest_like_list"))
                    .postJson(json)
            }.text().let {

                LogUtils.e(">>>> ", it)
                val entity: BaseEntity<MutableList<HomeDataEntity>> =
                    it.gsonList(HomeDataEntity::class.java)

                dataListResult.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }


    fun category(type: Int) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/book/book_type_all?type=${type}"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(">>> ", "category = " + it)
                val entity: BaseEntity<MutableList<CategoryEntity>> =
                    it.gsonList(CategoryEntity::class.java)

                dataCategoryResult.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }

    fun categoryDetails(
        bookState: String = "-1",
        labelTitle: String = "",
        pageNo: Int = 0,
        sortType: String = "-1",
        typeId: Int = 0,
        wordCount: String = "-1",
    ) {

        LogUtils.e(">>>> ", " bookState = " + bookState)
//        bookState 0连载1完结2停更 全部传-1
        //labelTitle 标签名字 全部传空字符串
        //pageNo
        //pageSize
        // sortType 排序类型 1:最高热度; 2:最近更新; 3:最新上架; 综合排序传-1
        //typeId 分类id 必传
        //wordCount 字数 1:50万字以下; 2:50-100万字; 3:100-300万字; 4:300万字以上; 全部传-1

        val map: MutableMap<String, String> = arrayMapOf()
        map["bookState"] = bookState.toString()
        map["labelTitle"] = labelTitle
        map["pageNo"] = pageNo.toString()
        map["pageSize"] = 10.toString()
        map["sortType"] = sortType.toString()
        map["typeId"] = typeId.toString()
        map["wordCount"] = wordCount.toString()
        val json = Gson().toJson(map)

        LogUtils.e(">>>> ", " json = " + json)

        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/book/app_book_list"))
                    .postJson(json)

            }.text().let {

                LogUtils.e(">>>> ", "it = " + it)
                val entity: BaseEntity<MutableList<HomeDataEntity>> =
                    it.gsonList(HomeDataEntity::class.java)
                dataCategoryDetailsResult.postValue(entity)

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }


    fun categoryLable(typeId: Int) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/book/app_book_list_filter?typeId=${typeId}"))
                    .post("".toRequestBody())
            }.text().let {

                LogUtils.e(">>> ", "lale = " + it)
                val entity: BaseEntity<CategorySortEntity> =
                    it.gsonNormal(CategorySortEntity::class.java)
                dataCategoryLableResult.postValue(entity)
            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }
}
